import React, { useState } from "react";
import { Layout, Menu } from "antd";
import * as Icon from "@ant-design/icons";
import MenuConfig from "../../config/index";
import { collapseMenu, selectMenuList } from "../../store/reducers/tab";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
const { Sider } = Layout;

// 动态获取icon
const iconToElement = (iconName) => React.createElement(Icon[iconName]);

// 处理菜单数据  items项设置必须要有key  icon  label
const menuItems = MenuConfig.map((item) => {
  // 没有子菜单
  const child = {
    key: item.path,
    icon: iconToElement(item.icon),
    label: item.label,
  };
  //  有子菜单
  if (item.children) {
    child.children = item.children.map((child) => {
      return {
        key: child.path,
        icon: iconToElement(child.icon),
        label: child.label,
      };
    });
  }

  return child;
});

const CommonAside = ({ collapsed }) => {
  // 创建dispatch
  const dispatch = useDispatch();
  const navigate = useNavigate();

  // 添加数据到store
  const setTabsList = (val) => {
    dispatch(selectMenuList(val));
  }
  // 切换菜单
  const selectMenu = (e) => {
    console.log("e", e);
    let data;
    MenuConfig.forEach((item) => {
      if(item.path == e.keyPath[e.keyPath.length - 1]){
        data = item;
        // 如果有二级菜单
        if(e.keyPath.length > 1){
          data = item.children.find(child => {
            return child.path == e.key
          })
        }
      }
    })

    setTabsList({
      path: data.path,
      name: data.name,
      label: data.label,
    })
    navigate(e.key);
  };

  return (
    <Sider
      collapsible //可折叠
      collapsed={collapsed}
      onCollapse={(value) => dispatch(collapseMenu(value))}
    >
      <h3 style={{ margin: 16, color: "white" }}>
        {collapsed ? "后台" : "后台管理系统"}
      </h3>
      <Menu
        theme="dark"
        defaultSelectedKeys={["1"]}
        mode="inline"
        items={menuItems}
        onClick={selectMenu}
      />
    </Sider>
  );
};

export default CommonAside;
